import {ipcMain, app} from 'electron'
import {postsTools} from "./postsTools"
const { spawn, exec } = require('child_process');

import {appConfig} from "./config"

const fs = require('fs');
const path = require('path');


const postsUtils = new postsTools(appConfig.VITEPRESS_PATH);


const getVitepressPort = () => {
    const package_file = path.join(appConfig.VITEPRESS_PATH, 'package.json');
    let json = JSON.parse(fs.readFileSync(package_file, 'utf-8'));
    return json.scripts['docs:dev'].split(' ')[5]
}

export const stopService = () => {
    const port = getVitepressPort()
    return new Promise((resolve, reject) => {
        exec(`netstat -ano | findstr ":${port}"`, (error, stdout, stderr) => {
            if (error) {
                return reject('未找到相关进程');
            }
            const lines = stdout.split('\n')[0].split(' ').filter(line => line.trim() !== '');
            const local_port = lines[1];
            const pid = lines[4].trim();
            const match = local_port.match(/:(\d+)/);
            if (match && match[1] == port){
                exec(`taskkill /PID ${pid} /F`, (error, stdout, stderr) =>{
                    if (error) {
                        return reject('停止服务失败');
                    }
                    
                    return resolve("服务已停止");
                    
                });
            }else{
                return reject('未找到相关进程');
            }
        });
    });
}

export const postsIPC = () => {
    ipcMain.handle('get:posts:tree', (event, navName) => {
        const navPath = path.join(appConfig.VITEPRESS_PATH, 'posts', navName)
        const result = [];
        if (!fs.existsSync(navPath)){
            return result;
        }else{
            return postsUtils.getDirectoryTree(navPath)
        }

    });

    ipcMain.handle('generate:vitepress:config', (event) => {
        postsUtils.generateConfig();
        return { success: true, message: 'Configuration files generated successfully!' };
        
    });

    ipcMain.handle('write:new:note', (event, noteId, content) => {
        const fullPath = path.join(appConfig.VITEPRESS_PATH, 'posts', noteId);

        if (fs.existsSync(fullPath)){
            return { success: false, msg: '文件已存在!' };
        }
        try {
            fs.writeFileSync(fullPath, content, 'utf-8');
            return { success: true, msg: '文件创建成功!' };
        }catch (e){
            return { success: false, msg: '文件创建失败!' };
        }
    });

    ipcMain.handle('save:note', (event, noteId, content) => {
        const fullPath = path.join(appConfig.VITEPRESS_PATH, 'posts', noteId);

        if (!fs.existsSync(fullPath)){
            return { success: false, msg: '错误, 当前文件不存在!' };
        }
        try {
            const regex = /!\[(.*?)\]\(http:\/\/localhost:\d+\/\?image=.*?(assets[^\)]+)\)/g;
            content = content.replace(regex, '![\$1](\$2)');

            fs.writeFileSync(fullPath, content, 'utf-8');
            return { success: true, msg: '文件创建成功!' };
        }catch (e){
            return { success: false, msg: '文件创建失败!' };
        } 
    });

    ipcMain.handle('delete:node', (event, noteId) => {
        const fullPath = path.join(appConfig.VITEPRESS_PATH, 'posts', noteId);
        if (fs.existsSync(fullPath)){
            fs.rmSync(fullPath, { recursive: true });
            return { success: true, message: '文件删除成功!' };
        }else{
            return { success: false, message: '文件删除失败' };
        }
    });


    ipcMain.handle('get:move:dir', async (event, stoppedID) => {
        const navPath = path.join(appConfig.VITEPRESS_PATH, 'posts')
        const result = [];
        if (!fs.existsSync(navPath)){
            return result;
        }else{
            return postsUtils.getMoveTree(navPath, stoppedID);
        }

    });

    ipcMain.handle('move:file', async (event, from, to) => {
        if (to.split('/').length <= 1){
            return { success: false, msg: "不允许文件移动到一级导航中" };
        }
        
        const fromPath = path.join(appConfig.VITEPRESS_PATH, 'posts', from);
        const toPath = path.join(appConfig.VITEPRESS_PATH, 'posts', to, path.basename(fromPath));

        try{
            let content = fs.readFileSync(fromPath, 'utf-8');
            const imageUrls = content.match(/!\[.*?\]\((.*?)\)/g);
            const imageUrlsList = imageUrls ? imageUrls.map(img => path.basename(img.match(/\((.*?)\)/)[1])) : [];
            const imageDir = path.join(path.dirname(fromPath), "assets/images")
            if (fs.existsSync(imageDir)){
                fs.readdirSync(imageDir).forEach(img => {
                    if (imageUrlsList.includes(img)){
                        const destImageDir = path.join(path.dirname(toPath), "assets/images");
                        if (!fs.existsSync(destImageDir)){
                            fs.mkdirSync(destImageDir, { recursive: true });
                        }
                        fs.copyFileSync(path.join(imageDir, img), path.join(destImageDir, img));
                    }
                })
            }
            
            await fs.promises.rename(fromPath, toPath);
            return { success: true, msg: '移动成功' };
        }catch (e){
            console.log(e);
            return { success: false, msg: e.message };
        }
 
    });
    ipcMain.handle('move:dir', async (event, from, to) => {
        const fromPath = path.join(appConfig.VITEPRESS_PATH, 'posts', from);
        const toPath = path.join(appConfig.VITEPRESS_PATH, 'posts', to, path.basename(fromPath));

        try{
            await fs.promises.rename(fromPath, toPath);
            return { success: true, msg: '移动成功' };
        }catch (e){
            console.log(e);
            return { success: false, msg: e.message };
        }

    });





    // --------------------------------------------------服务相关-------------------------------------------------- 
    ipcMain.handle('start:service', async (event) => {
        try{
            // 先把之前的进程给停了
            await stopService();
        }catch(e){
            console.log("没有进程运行，可以继续启动服务");
        }
        const nodeENV = process.resourcesPath.indexOf('\\node_modules\\') === -1
        ? { Path: path.join(process.resourcesPath, 'node-v20.18.1-win-x64') }
        : {};
        const web_process = spawn('npm.cmd', ['run', 'docs:dev'], {
            cwd: appConfig.VITEPRESS_PATH,
            env: { ...nodeENV},
            shell: true
        });        
        web_process.stdout.on('data', (data) => {
            event.sender.send('service:stdout:log', data.toString());
        });


        web_process.on('close', (code) => {
            event.sender.send('service:close:log', code);
        })
    
    });


    ipcMain.handle('stop:service', async (event) => { 
        try{
            const message = await stopService();
            return { success: true, message: message };
        }catch(e){
            return { success: false, message: e };
        }
    });

}
